import { useRef } from "react";
import clsx from "clsx";
import { useForm } from "../../../framework/common/context/metadata-context";
import { diffStyle } from "../../../framework/common/utils/diffStyle";
import { fieldFilter, fieldFilterNormal } from "../../../framework/common/utils/filter";
import RemarkTip from "../../RemarkTip";
import useOperationConnect from "../../../framework/common/lifecycle/useOperationConnect";

export default function Header({ wrapperRef, actualHeight, scale, fixedColum = 999, group, isFromFixedTable = false, fields }) {
  const form = useForm();
  let isPrint=(form.mode==="Print")
  const theadRef = useRef();

  if (fixedColum === 999) {
    form.subTableTheadRef[group.code] = theadRef; //冻结列组件也会触发，只需要记录正常子表的colgroup dom对象
  }

  //fixme: 设计时is_sys字段有些情况会丢失

  //根据标题样式获得子表标题的className
  function getStyleName(field) {
    let fieldTitleStyle = field?.designProps?.styleData?.fieldTitleStyle; //字段lable样式
    let fieldClsName = diffStyle(fieldTitleStyle, "fieldTitleStyle"); //根据配置得到lable的className
    if (!fieldClsName) {
      fieldClsName = form.fieldClsName; //没有自定义样式，就用全局的
    }
    return fieldClsName;
  }

  //编辑模式下子表删除列
  let operationCell = undefined;
  //  if(form.isDesign&&group.isDelete&&isFromFixedTable!==true){
  //    operationCell=<th>操作</th>
  //  }

  let allRowHiddenCount = 0;
  let normalFilterFields = fields.filter(fieldFilterNormal);
  let fixedColumCount = fixedColum;
  normalFilterFields.forEach((field, index) => {
    if (field.isAllRowhidden === true && index <= fixedColum) {
      allRowHiddenCount++;
    }
  });
  fixedColumCount = fixedColumCount - allRowHiddenCount;

  if (group.table_group_title === true) {
    //启用列表分组标题
    let skipedCol = 0;
    let filterFields = fields.filter(fieldFilterNormal);

    return (
      <thead>
        <tr>
          {filterFields.map((field, index) => {
            if (field.originColspan === undefined) {
              field.originColspan = field.colspan;
            } else {
              field.colspan = field.originColspan;
            }

            if (index >= fixedColumCount) return null;
            if (skipedCol > 0) {
              //合并列
              skipedCol--;
              return null;
            }
            //计算合并列
            if (field.colspan >= 2) {
              let hiddenCount = field.isHidden ? 1 : 0;
              for (let i = 0; i < field.colspan - 1; i++) {
                if (filterFields[index + 1 + i]?.isHidden == true || filterFields[index + 1 + i]?.isAllRowhidden === true) {
                  hiddenCount++;
                }
              }
              field.colspan = field.colspan - hiddenCount;

              if (field.colspan >= 2 - (field.isHidden ? 1 : 0)) skipedCol = field.originColspan - 1;
            }
            //隐藏列
            if (field.isHidden === true) {
              if (field?.designProps.groupTitle && field.colspan > 0) {
              } else {
                return null;
              }
            }
            //行数据全部隐藏会隐藏当前列
            if (field.isAllRowhidden === true) return null;

            let tableGroupTitleStyle = field?.designProps?.styleData?.tableGroupTitleStyle; //字段lable样式
            // if(field.code ==="days"){
            //   debugger
            // }
            let tableGroupTitleClsName = diffStyle(tableGroupTitleStyle, "tableGroupTitleStyle"); //根据配置得到lable的className
            return field.rowspan === 2 
            ? (
                <HeaderRowSpanTh key={index} showRemark={false} wrapperRef={wrapperRef} field={field} index={index} group={group} tableGroupTitleClsName={tableGroupTitleClsName}></HeaderRowSpanTh>
              ) 
            : field.colspan >= 2 - (field.isHidden ? 1 : 0) 
              ? (
                  <HeaderColSpanTh
                    key={index}
                    index={index}
                    wrapperRef={wrapperRef}
                    field={field}
                    group={group}
                    tableGroupTitleClsName={tableGroupTitleClsName}
                    filterFields={filterFields}
                  ></HeaderColSpanTh>
                ) 
                : (
                  <HeaderEmptyTh key={index} index={index} wrapperRef={wrapperRef} field={field} group={group} tableGroupTitleClsName={tableGroupTitleClsName}></HeaderEmptyTh>
                );
          })}
          {operationCell}
        </tr>

        <tr>
          {filterFields.map((field, index) => {
            if (index >= fixedColumCount) return null;
            if (field.isHidden === true || field.isAllRowhidden === true) return null; //<th className={clsx("col-title", getStyleName(field))} key={index}></th>;
            //合并行
            if (field.rowspan === 2) return null;
            return <HeaderTh table_group_title={true} key={index} showRemark={false} wrapperRef={wrapperRef} field={field} getStyleName={getStyleName} index={index} group={group}></HeaderTh>;
          })}
          {operationCell}
        </tr>
      </thead>
    );
  }
  return (
    <thead>
      <tr ref={theadRef} style={{ height: actualHeight }}>
        {fields.filter(fieldFilter).map((field, index) => {
          if (index >= fixedColumCount) return null;
          if (field.isHidden === true) return null;
          return <HeaderTh key={index} isPrint={isPrint} wrapperRef={wrapperRef} field={field} getStyleName={getStyleName} index={index} group={group}></HeaderTh>;
        })}
        {operationCell}
      </tr>
    </thead>
  );
}

/**
 * 
 * @description 正常表头
 */
function HeaderTh({ table_group_title=false,showRemark = true, wrapperRef, field, getStyleName, index, group ,isPrint}) {
  const thRef = useRef();
  const operationConnector = useOperationConnect(
    () => thRef.current.getBoundingClientRect(),
    () => {
      let thRect=thRef.current.getBoundingClientRect();
      let wrapperRect = wrapperRef.current.getBoundingClientRect();
      let firstRowRect;
      if(table_group_title){
        firstRowRect= thRef.current?.parentElement?.previousElementSibling?.getBoundingClientRect()
      }


      //不需要考虑合计列
      return {
        width: thRect.width,
        height:  wrapperRect.height-(firstRowRect?.height||0),
        left: thRect?.left,
        top: thRect?.top +(wrapperRef.current.scrollTop||0),
      };
    },
    {
      group,
      type: "cell-children",
      cell: field,
    }
  );
  return (
    <th ref={thRef} {...operationConnector} style={{minWidth:isPrint!=true&&(field.style.width+"px")}} className={clsx("col-title", getStyleName(field))} key={index}>
      {field?.designProps?.title || field?.name}
      {showRemark && <RemarkTip codePath={`form.data_range.children.${group.code}.${field.code}`}></RemarkTip>}
    </th>
  );
}

/**
 * 
 * @description 跨行表头
 */
function HeaderRowSpanTh({ wrapperRef, field, tableGroupTitleClsName, index, group }) {
  //fixme: is colspan with rowspan case exist? 
  const thRef = useRef();
  const operationConnector = useOperationConnect(
    () => thRef.current.getBoundingClientRect(),
    () => {
      let thRect = thRef.current.getBoundingClientRect();
      let wrapperRect = wrapperRef.current.getBoundingClientRect();
      //不需要考虑合计列
      return {
        width: thRect.width,
        height: wrapperRect.height,
        left: thRect?.left,
        top: thRect?.top+(wrapperRef.current.scrollTop||0),
      };
    },
    {
      group,
      type: "cell-children",
      cell: field,
    }
  );
  return (
    <th des="多行头合并" ref={thRef} {...operationConnector} className={clsx("col-title", tableGroupTitleClsName)} key={index} rowSpan={field.rowspan} colSpan={field.colspan}>
      {field?.designProps.title || field?.name}
      <RemarkTip codePath={`form.data_range.children.${group.code}.${field.code}`}></RemarkTip>
    </th>
  );
}

/**
 * 
 * @description 跨列表头
 */
function HeaderColSpanTh({ wrapperRef, field, tableGroupTitleClsName, index, group, filterFields }) {
  const thRef = useRef();
  const operationConnector = useOperationConnect(
    () => thRef.current.getBoundingClientRect(),
    () => {
      let thRect = thRef.current.getBoundingClientRect();
      let wrapperRect = wrapperRef.current.getBoundingClientRect();
      //不需要考虑合计列
      return {
        width: thRect.width,
        height:  wrapperRect.height,
        left: thRect?.left,
        top: thRect?.top+(wrapperRef.current.scrollTop||0),
      };
    },
    {
      group,
      type: "cell-colspan-children",
      cells: filterFields.slice(index, index + field.originColspan),
    }
  );
  return (
    <th ref={thRef} {...operationConnector} className={clsx("col-title", tableGroupTitleClsName)} key={index} rowSpan={field.rowspan} colSpan={field.colspan}>
      {field?.designProps.groupTitle}
    </th>
  );
}

/**
 * 
 * @description 空表头
 */
function HeaderEmptyTh({ wrapperRef, field, tableGroupTitleClsName, index, group }) {
  const thRef = useRef();
  const operationConnector = useOperationConnect(
    () => thRef.current.getBoundingClientRect(),
    () => {
      let thRect = thRef.current.getBoundingClientRect();
      let wrapperRect = wrapperRef.current.getBoundingClientRect();
      //不需要考虑合计列
      return {
        width: thRect.width,
        height:  wrapperRect.height,
        left: thRect?.left,
        top: thRect?.top+(wrapperRef.current.scrollTop||0),
      };
    },
    {
      group,
      type: "cell-children",
      cell: field,
    }
  );
  return (
    <th ref={thRef} {...operationConnector} className={clsx("col-title", tableGroupTitleClsName)} key={index} rowSpan={field.rowspan} colSpan={field.colspan}>
      {field?.designProps.groupTitle}
    </th>
  );
}
